<template>
  <div class="app-container">
    <el-card class="pag-container">
      <el-row>
        <el-col :span="7">
          <div style="font-size: 16px;font-weight: 600;">{{ rowData.companyName }}</div>
          <div style="margin-top: 10px;position: relative;">
            <Carousel v-bind="swiperData" style="position: absolute;top: 10px;"></Carousel>
          </div>
        </el-col>
        <el-col :span="14">
          <div style="font-size: 14px;text-align: left; box-sizing: border-box;padding: 10px 40px 10px 40px;">
            <el-row :gutter="10">
              <el-col :span="11">
                <span style="font-weight: bolder;font-size: 16px;">{{ rowData.carryCityName }}</span>
                <div style="margin-top: 20px;">
                  提箱城市：{{ rowData.carryCityName }}/{{ rowData.carryCountryName }}
                </div>
              </el-col>
              <el-col :span="2"><img style="text-align: center; width: 17px;"
                  src="@/assets/icons/svg/right.svg"></el-col>
              <el-col :span="11" style="text-align: right;">
                <span style="font-weight: 800;font-size: 16px;">{{ rowData.returnCityName }}</span>
                <div style="margin-top: 20px;">
                  还箱城市：{{ rowData.returnCityName }}/{{ rowData.returnCountryName }}
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="14">
                <table style="font-size: 14px;width: 600px;margin-top: 30px; text-align: left;">
                  <tbody>
                  <tr style="width: 200px;">
                    <td>租箱单价</td>
                    <td style="font-weight: 600;color: #ff0000;">{{unitCurrency}} {{ unitPrice }}</td>
                  </tr>
                  <tr>
                    <td>可结算币种</td>
                    <td style="font-weight: 600;"> {{ payCurrency }}</td>
                  </tr>
                  <tr>
                    <td>箱使期</td>
                    <td style="font-weight: 600;"> {{ rowData.boxUsagePeriod }} 天</td>
                  </tr>
                  <tr>
                    <td>箱型</td>
                    <td>
                      <el-radio-group v-model="param.boxType" @change="boxTypeChange">
                        <el-radio-button v-for="item in param.boxTypeList" :label="item.label" :key="item"
                          :value="item.value" />
                      </el-radio-group>
                    </td>
                  </tr>
                  <tr>
                    <td>箱况</td>
                    <td>
                      <el-radio-group v-model="param.boxCondition" @change="boxConditionChange">
                        <el-radio-button v-for="item in param.boxConditionList" :label="item.label" :key="item"
                          :value="item.value" />
                      </el-radio-group>
                    </td>
                  </tr>
                  <tr>
                    <td>超期费</td>
                    <td style="display:flex;align-items:center ">
                      <p style="overflow: hidden; white-space: nowrap;text-overflow: ellipsis; width: 180px">
                        超期1天，${{ rowData.overdueFeeDay }} /箱/天,
                        超期 {{ rowData.lossDay }} 天仍未还箱，
                        视为灭失，灭失费$ {{ rowData.lossFee }} 元
                      </p>
                      <el-tooltip :content="contentDay" effect="dark" placement="top">
                        <el-icon class="el-icon--right" :size="20">
                          <QuestionFilled />
                        </el-icon>
                      </el-tooltip>
                    </td>
                  </tr>
                  <tr v-if="showBtn">
                    <td>可租箱量</td>
                    <td style="display:flex;align-items:center ">
                      {{ inventory }}个
                      <el-input-number v-model="param.num" :min="0" :max="9999" @change="handleChange"  style="float: left;"/>
                      <el-tooltip :content="content" effect="dark" placement="top">
                        <el-icon class="el-icon--right" :size="20">
                          <QuestionFilled />
                        </el-icon>
                      </el-tooltip>
                      <!-- <span v-if="inventory == 0" style="color: red;"> 无库存 </span> -->
                    </td>
                  </tr>
                  <!-- <tr>
                    <td style="width:80px; ">结算账期</td>
                    <td>
                      <div class="marginTop10">
                        <p class="margin0">首次下单：先付后提</p>
                        <p class="margin0">多次下单：提后{{ rowData.period }}天内付</p>
                      </div>
                    </td>
                  </tr> -->
                  </tbody>
                </table>
                <div class="marginTB40">
                  <el-button v-if="showBtn" type="primary"
                    @click="handleSubmit">立即租箱</el-button>
                </div>
              </el-col>
            </el-row>
          </div>

        </el-col>
      </el-row>
    </el-card>

    <el-card class="pag-container">
      <span style="font-weight: 700;font-size: 15px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>租箱详情
      </span>
      <div class="titleInfo" style="font-weight: 700;font-size: 14px;margin-top:10px">集装箱介绍</div>
      <el-form inline style="margin-top: 10px;" label-position="left">
        <el-form-item label="箱型:">{{ boxTypeFilter(param.boxType) }}(HQ为高柜,GP为普柜)</el-form-item>
        <el-form-item label="箱况:">{{ boxConditionFilter(param.boxCondition) }}</el-form-item>
        <el-form-item label="箱使期:">{{ rowData.boxUsagePeriod }} 天</el-form-item>
        <el-form-item label="总重:">{{ param.boxType > 10 ? '30480' : '30480/32500' }} KG</el-form-item>
      </el-form>
    </el-card>

    <el-card class="pag-container">
      <span style="font-weight: 700;font-size: 15px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>图文详情
      </span>
      <div v-for="item in detailFileList" style="width:100%;  ">
        <div v-for="img in item.imgInfo" style="width:100%;text-align: center;">
          <img :src="img.url" style="width:750px;height:auto;margin-top: 10px" />
        </div>
        <div style="box-sizing: border-box;padding: 10px;">{{ item.textVal }}</div>
      </div>
    </el-card>

    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible" width="500">
      <el-form :model="param.form">
        <el-form-item label="签署人姓名">
          <el-input v-model="param.form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="签署人电话">
          <el-input v-model="param.form.code" placeholder="请输入验证码" />
        </el-form-item>
        <el-form-item>
          <div style="background-color: #FFF2E7;padding: 5px;box-sizing: border-box;width: 100%">
            <el-icon style="color: #2158F3;">
              <WarningFilled />
            </el-icon> 请确认签署人是否正确，更改签署人将重新发起签署！<br>
            <a href="#" style="padding-left: 20px;color: #7CAFFF;">E签宝协议签订教程</a>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="param.dialogVisible = false">取消</el-button>
          <el-button @click="handleSign">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="centerDialogVisible" title="提示" width="500" destroy-on-close center>
      <span>
        您还未完成企业实名认证，请您完成企业实名认证后，就可以进行相应业务功能操作啦！
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="goAuthenticate">企业实名认证</el-button>
        </div>
      </template>
      </el-dialog>
  </div>
</template>
<script lang="ts" setup>




import { computed, onActivated, onMounted, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import  Carousel from '@/components/carousel'
import { getBoxInfo } from '@/api/boxRent'
import orderInfo from '@/store/modules/order'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
const route = useRoute()
const props = defineProps({
  data: {
    type: Object,
    default: () => {
      return {}
    }
  }
})
const centerDialogVisible=ref(false)
const swiperData = reactive({
  list: [],
  config: {
    width:"100%",
    height:"450px"
  }
})
const param = reactive({
  dialogVisible: false,
  boxConditionList: [],
  boxTypeList: [],
  boxType: '',
  boxCondition: '',
  num: 0,
  page: 1,
  limit: 10
})
const content=ref('仅供参考，可超量下单，以联系集装箱公司为准')
const contentDay=ref('')
const inventory = computed(() => {
  let tagDataList = rowData.value.releaseRentPriceList
  if (!tagDataList) return 0
  let num = 0
  tagDataList.forEach((item: any) => {
    if (item.boxType == param.boxType && item.boxCondition == param.boxCondition) {
      num = item.inventory
    }
  })
  if (num < 0) num = 0
  return num
})
const payCurrency  = computed(() => {
  let currency = rowData.value.payCurrency || ""
    let newCurrency1 = currency.replace("USD","美元")
    let  newCurrency2 = newCurrency1.replace("CNY","人民币")
  return newCurrency2
    
})
const unitPrice = computed(() => {
  console.log("rowData.value",rowData.value)
  const tagDataList = rowData.value.releaseRentPriceList
  let price = 0
  if (!tagDataList) return 0
  let currency = ""
  tagDataList.forEach((item: any) => {
    if (item.boxType == param.boxType && item.boxCondition == param.boxCondition) {
        if(item.currency == "CNY"){
          currency = "¥"
        }else if(item.currency =="USD"){
          currency = "$"
        }
      price = item.unitPrice
    }
  })
  // toLocaleString 金额加逗号
  return (price.toLocaleString())
})

const unitCurrency = computed(()=>{
  const tagDataList = rowData.value.releaseRentPriceList
  if (!tagDataList) return 0
  let currency = ""
  tagDataList.forEach((item: any) => {
    if (item.boxType == param.boxType && item.boxCondition == param.boxCondition) {
        if(item.currency == "CNY"){
          currency = "¥"
        }else if(item.currency =="USD"){
          currency = "$"
        }
    }
  })
  // toLocaleString 金额加逗号
  return currency
})

// 立即租箱按钮 显示控制
const showBtn = computed(() => {
  const user = userStore.getUser()
  return user.companyId != rowData.value.companyId
})

onActivated(() => {
  console.log('onActivated')
  getSetBoxInfo()
})

// 初始化数据
const mainFileList = ref([])
const detailFileList = ref([])
const rowData = ref([])
const getSetBoxInfo = async () => {
  if(!route.query.releaseRentId) return
  let row = orderInfo().rowData
  if (row) {
    await getBoxInfo(route.query.releaseRentId).then((res: any) => {
      const result = res.data
      mainFileList.value = JSON.parse(result.mainFileList)
      swiperData.list = JSON.parse(result.mainFileList)
      detailFileList.value = JSON.parse(result.detailFileList)
      param.boxTypeList = getBoxTypes(result) // 可选箱型+默认值
      param.boxConditionList = getBoxCondition(result, param.boxType) // 箱况list
      param.num = 0
      rowData.value = result
      contentDay.value='超期1天，$'+rowData.value.overdueFeeDay+'/箱/天,超期'+rowData.value.lossDay+'天仍未还箱,视为灭失，灭失费$'+rowData.value.lossFee+'元'
    })
  }
}
// 实名认证
const goAuthenticate = () => {
  router.push('/enterpriseManage/realAuthentication')
  centerDialogVisible.value = false
}
//链接跳转
const handleLink = (url: string) => {
  orderInfo().setRowData(rowData.value)
  router.push('/company/companyInfo')
}

// 整合可选箱型+默认值
const getBoxTypes = (result: any) => {
  let arry: any = []
  let list: any = []
  result.releaseRentPriceList.forEach((el: any) => {
    if (!arry.includes(el.boxType)) {
      list.push({ value: el.boxType, label: boxTypeFilter(el.boxType) })
      arry.push(el.boxType)
    }
  })
  param.boxType = list[0].value //箱型默认
  return list
}
// 整合可选箱况(根据箱型)+默认值
const getBoxCondition = (result: any, boxType: any) => {
  let arry: any = []
  let list: any = []
  result.releaseRentPriceList.forEach((el: any) => {
    if (!arry.includes(el.boxCondition) && el.boxType == boxType) {
      list.push({ value: el.boxCondition, label: boxConditionFilter(el.boxCondition) })
      arry.push(el.boxCondition)
    }
  })
  param.boxCondition = list[0].value //箱况默认
  return list
}
//箱型变更
const boxTypeChange = (value: any) => {
  param.boxConditionList = getBoxCondition(rowData.value, param.boxType)
  param.num = 0
}
//箱况变更
const boxConditionChange = (value: any) => {
  param.num = 0
}
//
const handleChange = (value: Number) => {
  console.log(value)
}

//过滤
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{ value: 15, label: '适货' }, { value: 10, label: '次新' }, { value: 20, label: '混提' },{ value: 5, label: '全新' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 5, label: '40HQ' }, { value: 10, label: '40GP' }, { value: 15, label: '20HQ' }, { value: 20, label: '20GP' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
import { userSimpleList } from '@/api/user/index' 
// 立即租箱 
const router = useRouter();
const handleSubmit = () => {
  if(userStore.getUser() && userStore.getUser().examineStatus != '10'){
    centerDialogVisible.value = true
  }else{
    let data = {
      boxType: param.boxType,
      boxCondition: param.boxCondition,
      num: param.num,
      unitCurrency:unitCurrency.value,
      unitPrice: unitPrice.value,
      inventory: inventory.value
    }
    rowData.value.submitData = data
    orderInfo().setRowData(rowData.value)
    router.push('xiaDan')

  //   userSimpleList({}).then(res => {
  //   let userList = []
  //   res.data.forEach((item:any) => {
  //     let obj = {"userId":item.userId,"userName":item.nickname}
  //     userList.push(obj)
  //   })

  //   // row["userSimpleList"] = userList

  //   let data = {
  //     boxType: param.boxType,
  //     boxCondition: param.boxCondition,
  //     num: param.num,
  //     unitCurrency:unitCurrency.value,
  //     unitPrice: unitPrice.value,
  //     inventory: inventory.value
  //   }
  //   rowData.value.submitData = data
  //   orderInfo().setRowData(rowData.value)
  //   router.push('xiaDan')
    
  // }).catch(err => {
  //   console.log('err',err)
  // })

  }
 



 
};

// 签署
const handleSign = () => {
  console.log('handleSign')
  router.push('/EQianBao_success')
  param.dialogVisible = false
}

</script>
<style lang="scss" scoped>
.pag-container {
  margin-top: 20px;
  box-sizing: border-box;
  padding: 10px;
}
</style>